'''实例分割，将图像固定到一定尺寸'''
from PIL import Image
from osgeo import gdal
import numpy as np
import os
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import random
from tqdm import tqdm
import xml.etree.ElementTree as ET

def limit_value(a, b):
    if a < 1:
        a = 1
    if a > b:
        a = b - 1
    return a
# xml文件修改
def v_MirrorAnno(anno_path,scale,h,w,nw,nh):
    tree = ET.parse(anno_path)
    root = tree.getroot()

    objects = root.findall("object")
    for obj in objects:
        # 获取原值*scale（缩放因子）
        bbox = obj.find('bndbox')
        x1 = float(bbox.find('xmin').text) * scale
        y1 = float(bbox.find('ymin').text)* scale
        x2 = float(bbox.find('xmax').text)* scale
        y2 = float((bbox.find('ymax').text))* scale
        # 进行值变换
        top = (h - nh) // 2
        ymin = int(y1 + top)
        ymax = int(y2 + top)
        left = (w - nw) // 2
        xmin = int(x1 + left)
        xmax = int(x2 + left)
        bbox.find('xmin').text = str(int(xmin))
        bbox.find('ymin').text = str(int(xmax))
        bbox.find('xman').text = str(int(ymin))
        bbox.find('ymax').text = str(int(ymax))
    tree.write(anno_path)  # 保存修改后的XML文件
# 图像缩放
def letterbox_image(Imgfiles_path,image, size,modes,xml_path):
    # 对图片进行resize，使图片不失真。在空缺的地方进行padding
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)
    image = image.resize((nw,nh), Image.BICUBIC)
    new_image = Image.new(modes, size, (128,128,128))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    v_MirrorAnno(xml_path, scale, h, w, nw, nh)
    img1 = Image.fromarray(new_image)
    img1.save(Imgfiles_path)

# -------------------总处理函数--------------------------
def Data_read(voc_path):
    # 数据读取
    # Annotations
    Anno_path = os.path.join(voc_path, 'Annotations')
    # JPEGImages
    JPEGI_path = os.path.join(voc_path, 'JPEGImages')
    # SegmentationClass
    SegClass_path = os.path.join(voc_path, 'SegmentationClass')
    # SegmentationObject
    SegObj_path = os.path.join(voc_path, 'SegmentationObject')
    # TXT文件路径
    # 语义分割
    SegT_TXT = os.path.join(voc_path, 'ImageSets', 'Segmentation', 'train.txt')
    SegV_TXT = os.path.join(voc_path, 'ImageSets', 'Segmentation', 'val.txt')
    Segsum_TXT = os.path.join(voc_path, 'ImageSets', 'Segmentation', 'trainval.txt')
    # 实例分割
    InsegT_TXT = os.path.join(voc_path, 'ImageSets', 'Main', 'train.txt')
    InsegV_TXT = os.path.join(voc_path, 'ImageSets', 'Main', 'val.txt')
    Insegsum_TXT = os.path.join(voc_path, 'ImageSets', 'Main', 'trainval.txt')
    with open(os.path.join(Insegsum_TXT), "r") as f:
        file_names = [x.strip() for x in f.readlines() if len(x.strip()) > 0]
        # 遍历文件列表
        for name in tqdm(range(len(file_names))):
            # img
            Imgfiles_path = os.path.join(JPEGI_path, file_names[name] + '.tif')
            im_width, im_height, im_bands, im_data, im_geotrans, im_proj = Raster.readRaster(Imgfiles_path)
            # 对RGB图像进行缩放
            lett
            erbox_image(Imgfiles_path,im_data, [512,512], 'RGB',xml_path)
            mask_path = os.path.join(SegObj_path, file_names[name] + '.tif')




            mask_width, mask_height, mask_bands, mask_data, mask_geotrans, mask_proj = Raster.readRaster(mask_path)
            # anno_xml
            xml_path = os.path.join(Anno_path, file_names[name] + '.xml')











    if __name__ == "__main__":
        # 数据所在的文件夹
        data_path = r'E:\01工作空间\VOCdevkit\pound_sufuce\pound_sufuce'